package com.fattyCorps.game.service.arena;


import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Data
public class Arena {
    // 玩家id->玩家竞技场信息
    private HashMap<Integer, ArenaElem> arenaMap = new HashMap<>();
    // 玩家的排名表，保存玩家id
    private List<Integer> arenaNos = new ArrayList<>();

    // 獲取某用戶前面幾位用戶信息
    public List<ArenaElem> getNear(int playerId, int size) {
        synchronized (arenaMap) {
            ArenaElem arenaPlayer = arenaMap.get(playerId);
            if (arenaPlayer == null) {
                return null;
            }

            int no = arenaPlayer.getNo();
            List<ArenaElem> nearPlayerList = new ArrayList<>();
            if (no - size > 0) {
                for (int i=0; i<size; i++) {
                    int d = i + 1;
                    int nearNo = no - d;
                    int nearIndex = nearNo - 1;
                    nearPlayerList.add(arenaMap.get(arenaNos.get(nearIndex)));
                }
            }

            return nearPlayerList;
        }
    }

    // 添加
    public void add(ArenaElem player) {
        synchronized (arenaMap) {
            if (arenaMap.get(player.getPlayerId()) != null) {
                return;
            }

            int no = arenaMap.size() + 1;
            player.setNo(no);
            arenaMap.put(player.getPlayerId(), player);
            arenaNos.add(player.getPlayerId());
        }
    }

    // 交换
    public void exchange(int playerIdA, int playerIdB) {
        synchronized (arenaMap) {
            ArenaElem arenaPlayerA = arenaMap.get(playerIdA);
            if (arenaPlayerA == null) {
                return;
            }

            ArenaElem arenaPlayerB = arenaMap.get(playerIdB);
            if (arenaPlayerB == null) {
                return;
            }

            int ANo = arenaPlayerA.getNo();
            int BNo = arenaPlayerB.getNo();
            arenaPlayerA.setNo(arenaPlayerB.getNo());
            arenaPlayerB.setNo(ANo);

            arenaNos.set(ANo, arenaPlayerB.getPlayerId());
            arenaNos.set(BNo, arenaPlayerA.getPlayerId());
        }
    }
}